var uploadFileSize = 1024 * 1024 * 15; //上传文件限制15m
import video from '@/common/utils.js'

function getSuffix(filename) {
	let pos = filename.lastIndexOf('.');
	let suffix = '';
	if (pos != -1) {
		suffix = filename.substring(pos);
	}
	return suffix;
}

function getFileName(file, filename) {
	return (
		file + Math.random()
		.toString(36)
		.substring(3, 20) + new Date().getTime() +
		getSuffix(filename)
	);
}
export function uploadImg(file) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: function(res) {
				let Imgsrc = res.tempFilePaths[0]; // 第一张图片
				let fileName = getFileName(file, Imgsrc); // 自定义上传后的文件名称
				fileUpload("image", Imgsrc, fileName).then(res => {
					resolve(res)
				}).catch(err => {
					reject(err)
				});
			}
		})
	})
}

function getCurrentTime() {
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds();

	// 将时、分、秒转换为两位数的格式
	if (hours < 10) {
		hours = "0" + hours;
	}
	if (minutes < 10) {
		minutes = "0" + minutes;
	}
	if (seconds < 10) {
		seconds = "0" + seconds;
	}

	var currentTime = hours + minutes + seconds;
	return currentTime;
}
export function uploadVid(file, data, id, token, name) {
	return new Promise((resolve, reject) => {
		try {
			let buttons = [{
				title: '录制'
			}, {
				title: '从相册选择'
			}]
			plus.nativeUI.actionSheet({
				cancel: "取消",
				buttons
			}, async e => {
				if (e.index == 1) {
					// 获取Module
					// var recordModule = uni.requireNativePlugin("CH-RecordMedia")
					// // 设置配乐列表
					// recordModule.setMusics(musics, (result) => {
					// })
					// // 打开录制界面
					// recordModule.goRecordPage((result) => {
					//     console.log(result)
					//     this.video= result.data.video
					//     this.image= result.data.image
					// })


					video.camera({
						time: 36000,
						data,
						id,
						file,
						token,
						name,
						success: e => {
							let videoSrc = e.fullPath
							let fileName = getFileName(file, videoSrc);
							fileUpload("video", videoSrc, fileName, data).then(res => {
								resolve(res)
							}).catch(err => {
								reject(err)
							});
						},
						fail: e => {
							 console.log(e);
						}
					})

				} else if (e.index == 2) {
					uni.chooseVideo({
						count: 1,
						compressed: true,
						sourceType: ['album'],
						success: res => {
							let videoSrc = res.tempFilePath;
							// if (res.size > uploadFileSize) {
							// 	uni.showToast({
							// 		title: '文件大小超过系统上传限制：15M',
							// 		icon: 'none',
							// 		duration: 1000
							// 	});
							// 	return;
							// }
							let fileName = getFileName(file, videoSrc);
							fileUpload("video", videoSrc, fileName, data).then(res => {
								resolve(res)
							}).catch(err => {
								reject(err)
							});
						},
						fail: (err) => {
							reject(err)
							uni.showToast({
								title: '取消选择视频',
								icon: 'none',
								duration: 2000
							});
						}
					})
				}
			})
		} catch (e) {
			console.log(e)
		}
	})
}

function captureVideo() {
	return new Promise((reslove, reject) => {
		var TIMEOUT = 0;
		const systemInfo = uni.getSystemInfoSync()
		if (systemInfo.osName === 'android') {
			var VIDEOZOOM = 200;
			var MediaStore = plus.android.importClass("android.provider.MediaStore");
			var Intent = plus.android.importClass("android.content.Intent");
			var intent = new Intent("android.media.action.VIDEO_CAPTURE");
			intent.putExtra("android.intent.extra.videoQuality", 0);
			intent.putExtra("android.intent.extra.durationLimit", TIMEOUT);

			var main = plus.android.runtimeMainActivity();
			main.startActivityForResult(intent, VIDEOZOOM);
			main.onActivityResult = function(requestCode, resultCode, data) {
				var context = main;
				plus.android.importClass(data);
				var uri = data.getData();
				var resolver = context.getContentResolver();
				plus.android.importClass(resolver);
				var cursor = resolver.query(uri, null, null, null, null);
				plus.android.importClass(cursor);
				cursor.moveToFirst();
				var column = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
				var path = cursor.getString(column);
				if (path) {
					reslove(path)
				} else {

				}
			}
		} else {
			var cmr = plus.camera.getCamera();
			var res = cmr.supportedVideoResolutions[0];
			var fmt = cmr.supportedVideoFormats[0];
			cmr.startVideoCapture(path => {
				reslove(path)
			}, error => {

			}, {
				resolution: res,
				format: fmt,
				filename: "_downloads/ibos/video/",
				videoMaximumDuration: TIMEOUT
			});

		}
	})
}
// 文件上传
export function fileUpload(type, path, stroeAs, data) {
	uni.showLoading({
		title: '文件上传中'
	});
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: 'https://yuyin-online.oss-cn-shanghai.aliyuncs.com', //后台返回的阿里云存储的上传地址
			filePath: path,
			fileType: type,
			name: 'file',
			formData: {
				key: stroeAs, //文件名
				policy: data.policy, //后台获取超时时间
				OSSAccessKeyId: data.accessid, //后台获取临时ID
				success_action_status: '200', //让服务端返回200,不然，默认会返回204
				signature: data.signature //后台获取签名
			},

			success: res => {
				uni.hideLoading();
				resolve(stroeAs) // 返回保存在阿里oss上的地址
			},
			fail: err => {
				uni.hideLoading();
				uni.showModal({
					content: JSON.stringify(err),
					showCancel: false
				});
				reject(err)
			}
		});
	});
}